package com.awccis.common.utils;

import okhttp3.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * @author yiyingcanfeng
 */
public class OKHttpUtil {

    public static final MediaType JSON = MediaType.parse("application/json;charset=utf-8");

    /**
     * 发起get请求
     *
     * @param url url
     * @param type 请求字符串数据还是二进制数据
     * @return 字符串
     */
    public static Object get(String url, int type) {
        switch (type) {
            case Constants.REQUEST_STRING:
                return stringGet(url);
            case Constants.REQUEST_STREAM:
                return streamGet(url);
            default:
                return "";
        }
    }

    /**
     * 发起post请求
     * @param syncOrAsync 同步请求还是异步请求
     * @param url            url
     * @param requestFormMap 键值对形式的表单数据
     * @return 字符串
     */
    public static String post(String url,int syncOrAsync, HashMap<String, String> requestFormMap,HashMap<String, String> header) throws IOException {
        return stringPost(url,syncOrAsync, requestFormMap,header);
    }

    /**
     * 发送post请求，获取字符数据
     *
     * @param url         url
     * @param syncOrAsync 同步请求还是异步请求
     * @param json        json数据
     * @return json字符串
     * @throws IOException IOException
     */
    public static String post(String url, int syncOrAsync, String json) throws IOException {
        return jsonPost(url, syncOrAsync, json);
    }

    /**
     * 发起get请求，获取字符数据
     *
     * @param url url
     * @return 字符串
     */
    public static String stringGet(String url) {
        String result = "";
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.body() != null) {
                result = response.body().string();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 发起get请求,获取二进制数据
     *
     * @param url url
     * @return InputStream
     */
    public static InputStream streamGet(String url) {
        InputStream is = null;
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(url).build();
        try {
            Response response = client.newCall(request).execute();
            if (response.body() != null) {
                is = response.body().byteStream();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return is;
    }

    /**
     * 发送httppost请求，获取字符数据
     * @param syncOrAsync 同步请求还是异步请求
     * @param url            url
     * @param requestFormMap 键值对形式的数据
     * @return 字符串数据
     */
    public static String stringPost(String url,int syncOrAsync, HashMap<String, String> requestFormMap,HashMap<String, String> header) throws IOException {
        final String[] result = {""};
        Headers headerBuild = Headers.of(header);
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : requestFormMap.keySet()) {
            builder.add(key, requestFormMap.get(key));
        }
        OkHttpClient httpClient = new OkHttpClient();
        Request request;
        RequestBody requestBody = builder.build();
        if (header == null) {
            request = new Request.Builder().url(url).post(requestBody).build();
        } else {
            request = new Request.Builder().url(url).post(requestBody).headers(headerBuild).build();
        }

        //同步请求
        return getString(syncOrAsync, result, httpClient, request);
    }

    /**
     * 发送post请求，获取字符数据
     *
     * @param url         url
     * @param syncOrAsync 同步请求还是异步请求
     * @param json        json数据
     * @return json字符串
     * @throws IOException IOException
     */
    public static String jsonPost(String url, int syncOrAsync, String json) throws IOException {
        final String[] result = {""};
        OkHttpClient httpClient = new OkHttpClient();
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder().url(url).post(body).build();

        //同步请求
        return getString(syncOrAsync, result, httpClient, request);
    }

    /**
     *
     * @param syncOrAsync 同步请求还是异步请求
     * @param result result
     * @param httpClient httpClient
     * @param request request
     * @return 字符串
     * @throws IOException IOException
     */
    private static String getString(int syncOrAsync,final String[] result, OkHttpClient httpClient, Request request) throws IOException {
        if (syncOrAsync == Constants.SYNC) {
            Response response = httpClient.newCall(request).execute();
            if (response.isSuccessful()) {
                if (response.body() != null) {
                    result[0] = response.body().string();
                }
            } else {
                throw new IOException("error");
            }

            //异步请求
        } else if (syncOrAsync == Constants.ASYNC) {
            Call call = httpClient.newCall(request);
            call.enqueue(new Callback() {

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    if (response.body() != null) {
                        result[0] = response.body().string();
                    }
                }

                @Override
                public void onFailure(Call call, IOException e) {

                }
            });
        }
        return result[0];
    }
}
